package com.heimo.babyage;

import java.util.Date;

import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.util.Log;
import android.view.View;
import android.widget.RemoteViews;

import com.heimo.babyage.core.DateHelper;
import com.heimo.babyage.core.LogHelper;
import com.heimo.babyage.core.PrefHelper;
import com.heimo.babyage.core.date.CorrectDate;
import com.heimo.babyage.ui.framegrid.FramePickerAdapter;

public class BabyAgeWidgetProvider extends AppWidgetProvider {

	/*
	 * onReceive()
	 * 
	 * (1)broadcast when one or more AppWidget instances have been deleted
	 * ACTION:android.appwidget.action.APPWIDGET_DELETED
	 * 
	 * (2)broadcast, which is sent when the last AppWidget instance for this
	 * provider is deleted ACTION:android.appwidget.action.APPWIDGET_DISABLED
	 * 
	 * (3)broadcast when the a AppWidget for this provider is instantiated
	 * ACTION:android.appwidget.action.APPWIDGET_ENABLED
	 * 
	 * (4)broadcast when this AppWidget provider is being asked to provide
	 * RemoteViews for a set of AppWidgets
	 * ACTION:android.appwidget.action.APPWIDGET_UPDATE
	 */

	private static final String TAG = "BabyAgeWidgetProvider";

	@Override
	public void onReceive(Context ctx, Intent intent) {
		LogHelper.log(TAG, "[onReceive] action : " + intent.getAction());
		super.onReceive(ctx, intent);
		String eventName = ctx.getResources().getString(
				R.string.widget_event_name);
		// DO UPDATE
		if (eventName.equals(intent.getAction())
				|| intent.getAction().equals(Intent.ACTION_TIME_CHANGED)
				|| intent.getAction().equals(Intent.ACTION_TIMEZONE_CHANGED)) {
			AppWidgetManager appWidgetManager = AppWidgetManager
					.getInstance(ctx);
			ComponentName thisAppWidget = new ComponentName(
					ctx.getPackageName(), BabyAgeWidgetProvider.class.getName());
			int[] appWidgetIds = appWidgetManager
					.getAppWidgetIds(thisAppWidget);
			onUpdate(ctx, appWidgetManager, appWidgetIds);

		}
	}

	@Override
	public void onEnabled(Context ctx) {
		super.onEnabled(ctx);
		LogHelper.log(TAG, "[onEnabled]");
		// RENEW TIMMER
		ctx.startService(getBabyAgeWidgetService(ctx));
	}

	@Override
	public void onDisabled(Context ctx) {
		super.onDisabled(ctx);
		LogHelper.log(TAG, "[onDisabled]");
		ctx.stopService(getBabyAgeWidgetService(ctx));
	}

	@Override
	public void onDeleted(Context ctx, int[] appWidgetIds) {
		super.onDeleted(ctx, appWidgetIds);
		LogHelper.log(TAG, "[onDeleted]");
		for (int appWidgetId : appWidgetIds) {
			LogHelper.log(TAG, "[onDeleted] id : " + appWidgetId);
			PrefHelper.fnDeletePref(ctx, appWidgetId);
		}
	}

	@Override
	public void onUpdate(Context ctx, AppWidgetManager appWidgetManager,
			int[] appWidgetIds) {
		// LogHelper.log(TAG, "[onUpdate]");

		// Get all widget id(s)
		ComponentName thisWidget = new ComponentName(ctx,
				BabyAgeWidgetProvider.class);
		int[] allWidgetIds = appWidgetManager.getAppWidgetIds(thisWidget);

		for (int widgetId : allWidgetIds) {
			LogHelper.log(TAG, "onWidget Update ID : " + widgetId);

			RemoteViews rv = new RemoteViews(ctx.getPackageName(),
					R.layout.widget_layout_1);
			
			// Update Text Size
			int size = PrefHelper.fnLoadTextSizePref(ctx, widgetId);
			rv.setFloat(R.id.counter_text, "setTextSize", size);

			// Update Text Color
			int color = PrefHelper.fnLoadTextColorPref(ctx, widgetId);
			rv.setInt(R.id.counter_text, "setTextColor", color);
			
			// Update Age
			Date d = PrefHelper.fnLoadBDayPref(ctx, widgetId);
			int pattern = PrefHelper.fnLoadTextPatternPref(ctx, widgetId);
			CorrectDate cAge = DateHelper.getCorrectedDate(d, new Date());
			String ageText = "";
			switch(pattern){
				case 1:
					int numberOfDay = DateHelper.getCorrectedDay(new Date(), d);
					ageText = String.valueOf(numberOfDay) + " d";
					break;
				case 2:
					ageText = String.format("%.1f", cAge.getGetAgeInMonthBase()) + " m";
					break;
				case 3:
					ageText = String.format("%.1f", cAge.getGetAgeInYearBase()) + " y";
					break;
				case 4:
					int numberOfDay2 = DateHelper.getCorrectedDay(new Date(), d);
					ageText = String.valueOf(numberOfDay2/7)+ " wk";
					break;
				default:
					ageText = cAge.toString();
					break;
			}
			rv.setTextViewText(R.id.counter_text, ageText);
			
			// Update Alpha
			int alpha = PrefHelper.fnLoadAlphaPref(ctx, widgetId);
			rv.setInt(R.id.baby_img, "setAlpha", alpha);
			
			// Update Overlay
			int framePos = PrefHelper.fnLoadFramePref(ctx, widgetId);
			if(framePos==0){
				rv.setViewVisibility(R.id.overlay, View.GONE);
			}else{
				rv.setViewVisibility(R.id.overlay, View.VISIBLE);
				FramePickerAdapter fpa = new FramePickerAdapter(ctx);
				int imgID = fpa.getImageIdByPos(framePos);
				rv.setImageViewResource(R.id.overlay, imgID);
			}
			
			// Update Image
			Bitmap bm = PrefHelper.fnLoadImage(ctx, widgetId);
			rv.setImageViewBitmap(R.id.baby_img, bm);

			// Setup OnClick Listener
			rv.setOnClickPendingIntent(R.id.entire_widget,
					fnGetPendingIntent(ctx, widgetId));

			// RENEW TIMMER
			ctx.startService(getBabyAgeWidgetService(ctx));

			// appWidgetManager.updateAppWidget(widgetId, rv);
			AppWidgetManager.getInstance(ctx).updateAppWidget(widgetId, rv);
		}
	}

	private PendingIntent fnGetPendingIntent(Context ctx, int appWidgetId) {
		Log.v(TAG, "[fnGetPendingIntent] ID : " + appWidgetId);
		Intent i = new Intent(ctx, PreferenceActivity.class);
		i.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);

		// PendingIntent pendingIntent = PendingIntent.getActivity(ctx, 0,
		// i, PendingIntent.FLAG_UPDATE_CURRENT);

		PendingIntent pi = PendingIntent.getActivity(ctx, appWidgetId, i,
				PendingIntent.FLAG_UPDATE_CURRENT);

		/*
		 * PendingIntent.FLAG_ONE_SHOT - Make new Activity
		 * PendingIntent.FLAG_UPDATE_CURRENT - Reuse the old Activity
		 * PendingIntent.FLAG_CANCEL_CURRENT - If current exists, discard and
		 * create new Intent.FLAG_ACTIVITY_NO_HISTORY - your activity will not
		 * remain on the stack after another activity covers it
		 */
		return pi;
	}

	/*
	 * Private function
	 */
	private Intent getBabyAgeWidgetService(Context ctx) {
		return new Intent(ctx, BabyAgeWidgetService.class);
	}
}